//{include file=".layers.js"}//
(function () {
    document.write('<script type="text/javascript" src="base.js"></script>');
    var core = ecui,
        ui = core.ui,
        util = core.util,
        dom = core.dom,
        isToucher = document.ontouchstart !== undefined,
        isPointer = !!window.PointerEvent, // 使用pointer事件序列，请一定在需要滚动的元素上加上touch-action:none
        iosVersion = /(iPhone|iPad).*?OS (\d+(_\d+)?)/i.test(navigator.userAgent) ? +(RegExp.$2.replace('_', '.')) : undefined,
        QQVersion = /QQLiveBrowser\/(\d+\.\d)/i.test(navigator.userAgent) ? +RegExp.$1 : undefined,
        ddCode,
        errorMsg = '请使用钉钉扫码绑定';


    // 解析url参数
    var paramMap = {},
        params = location.search.slice(1).split('&').filter(function (item) {
            return item !== '';
        });

    // eslint-disable-next-line no-cond-assign
    for (var i = 0, item; item = params[i++]; ) {
        var arr = item.split('=');
        if (arr.length > 1) {
            paramMap[arr[0]] = arr[1];
        } else if (arr.length === 1) {
            paramMap[arr[0]] = true;
        }
    }
    ecui.ready(function () {

        ecui.$('bindBtn').onclick = function () {
            console.log('点击');
            if (!ddCode) {
                ecui.tip('warn', errorMsg);
                return false;
            }
            mao.util.addLoading();
            ecui.esr.request(
                util.stringFormat('data@GET /erp-management/dingding/relevate/staff?code={0}&staffId={1}', ddCode, paramMap.staffId),
                function () {
                    mao.util.removeLoading();
                    var code = ecui.esr.getData('data_CODE');
                    var data = ecui.esr.getData('data');
                    if (code === 0) {
                        ecui.tip('success', '绑定成功');
                        window.localStorage.setItem('userId', data.userId);
                        location.href = 'index.html';
                    }
                }.bind(this),
                function () {
                    mao.util.removeLoading();
                }.bind(this)
            );
        };
        ecui.$('tip').innerHTML = util.stringFormat('确认要将该钉钉账号绑定到erp账号 <span class="name primary-text">{0}</span> ？', decodeURIComponent(paramMap.staffName));

        dd.ready(function () {
            console.log('获取code');
            mao.util.addLoading();
            dd.runtime.permission.requestAuthCode({
                corpId: mao.info.corpId,
                onSuccess: function(result) {
                    mao.util.removeLoading();
                    ddCode = result.code;
                    console.log('获取到code : ' + ddCode);
                },
                onFail: function(err) {
                    mao.util.removeLoading();
                    console.log('requestAuthCode', err);
                    errorMsg = '请切换到您当前所在企业';
                    ecui.tip('warn', '请切换到您当前所在企业');
                }
            })
        });
    });

}());
